package org.jiuling.tencentcloud.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import org.jiuling.basics.validation.StringVerify;
import org.jiuling.crypto.algorithm.UUID;
import org.jiuling.tencentcloud.cos.client.builder.CosStsClientBuilder;
import org.jiuling.tencentcloud.cos.client.factory.CosClientFactory;
import org.jiuling.tencentcloud.cos.config.TencentCosConfig;
import org.jiuling.tencentcloud.cos.config.TencentCosStsConfig;

import java.io.IOException;
import java.io.InputStream;

/**
 * 腾讯云对象存储
 * @author 紫灵
 * @date 2024年02月22日 23时05分28秒
 */
public class TencentCloudCos {

    /** 腾讯云对象存储配置 */
    private final TencentCosConfig tencentCosConfig;
    /** Cos客户端工程 */
    private final CosClientFactory cosClientFactory;

    public TencentCloudCos(TencentCosConfig tencentCosConfig,CosClientFactory cosClientFactory) {
        this.tencentCosConfig = tencentCosConfig;
        this.cosClientFactory = cosClientFactory;
    }

    /**
     * 上传对象
     * @param inputStream 输入流
     * @param fileType 文件类型
     * @param bucket 桶
     * @param fileSuffix 文件后缀
     * @return 文件Key
     */
    public String uploadObject(InputStream inputStream,String fileType,String bucket,String fileSuffix) {
        if(StringVerify.isBlank(bucket)){
            bucket = tencentCosConfig.getBucketName();
        }
        String fileName = UUID.getUUIDIsWithoutLine()+fileSuffix;
        // 创建上传Object的Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
//        // - 使用输入流存储，需要设置请求长度
//        objectMetadata.setContentLength(inputStream.available());
        // - 设置缓存
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setContentDisposition("inline");
        // - 设置Content-Type
        objectMetadata.setContentType(fileType);
        COSClient cosClient = cosClientFactory.builderCosClient();
        //上传文件
        PutObjectResult putResult = cosClient.putObject(bucket, fileName, inputStream, objectMetadata);
        //关闭 cosClient，并释放 HTTP 连接的后台管理线程
        cosClient.shutdown();
        return fileName;
    }

    /**
     * 获取临时对象地址
     * @param bucket 桶
     * @param objectKey 对象key
     * @return 地址
     */
    public String getTemporaryObjectUrl(String bucket,String objectKey){
        String objectUrl = null;
        try {
            objectUrl = tencentCosConfig.getUrlPath()+"/"+cosClientFactory.builderCosClient().getObject(bucket,objectKey).getKey();
        }catch (CosServiceException ignored){
        }
        return objectUrl;
    }

    /**
     * 删除对象
     * @param bucket 桶
     * @param objectKey 对象key
     */
    public void deleteObject(String bucket,String objectKey){
        if(StringVerify.isBlank(bucket)){
            bucket = tencentCosConfig.getBucketName();
        }
        cosClientFactory.builderCosClient().deleteObject(bucket, objectKey);
    }

    public static void main(String[] args) throws IOException {
        TencentCosConfig tencentCosConfig = TencentCosConfig.builder()
                .addUrlPath("https://logistic-1310184619.cos.ap-guangzhou.myqcloud.com")
                .addSecretId("AKIDPisrkXPGLSan9X3gN4gHmBWFGNd2OsQ2")
                .addSecretKey("2Ai9RYVHtSq35ziy40mMpLm6JLFzYyFN")
                .addBucketAddr("ap-guangzhou")
                .addBucketName("logistic-1310184619")
                .build();
        CosClientFactory cosClientFactory = new CosStsClientBuilder(
                tencentCosConfig,
                TencentCosStsConfig.builder()
                        .addAllowActions(new String[]{}).build());
        TencentCloudCos tencentCloudCos = new TencentCloudCos(tencentCosConfig,cosClientFactory);
        System.out.println(tencentCloudCos.getTemporaryObjectUrl(
                "logistic-1310184619",
                "117845e1d746b487094a2d4d1908b455d.jpeg"
        ));
        // 简单上传
//        "name/cos:PutObject",
//                "name/cos:GetObject",
//                "name/cos:DeleteObject",
//                System.out.println(tencentCloudCos.uploadObject(
//                new FileInputStream("C:\\Users\\LYM\\Downloads\\wKgBs1gDDt6AKrTbABPsiRWqoFw41.jpeg"),
//                "image/jpeg",
//                null,
//                ".jpeg"
//        ));
    }

}